/**
 * // Definition for a Node.
 * function Node(val, neighbors) {
 *    this.val = val === undefined ? 0 : val;
 *    this.neighbors = neighbors === undefined ? [] : neighbors;
 * };
 */

/**
 * @param {Node} node
 * @return {Node}
 */
var cloneGraph = function(node) {
    const visited = new Map()
    return dfs(node)

    function dfs(node) {
        if (!node) return null
        if (visited.has(node)) return visited.get(node)

        const newNode = new Node(node.val)
        visited.set(node, newNode)

        for (let neighbor of node.neighbors) {
            newNode.neighbors.push(dfs(neighbor))
        }
        return newNode
    }
}